﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace UnitControls {
    /// <summary>
    /// Interaction logic for RatioInput.xaml
    /// </summary>
    public partial class RatioInput : UserControl {
        private double m_Value;
        public double Value {
            get {
                return m_Value;
            }

            set {
                m_Value = value;
                UpdateTextBox();
            }
        }

        private event EventHandler m_OnChange;
        public event EventHandler OnChange {
            add {
                lock ( this ) {
                    m_OnChange += value;
                }
            }
            remove {
                lock ( this ) {
                    m_OnChange -= value;
                }
            }
        }

        public RatioInput() {
            InitializeComponent();
        }

        public void UpdateTextBox() {
            if ( InputBox.IsFocused ) return;
            InputBox.Text = (m_Value * 100.0).ToString();

            if ( this.IsLoaded && this.IsEnabled && m_OnChange != null )
                m_OnChange( this, new EventArgs() );
        }

        private void BtnMinus_Click( object sender, RoutedEventArgs e ) {
            Value -= 0.01;
            UpdateTextBox();
        }

        private void BtnPlus_Click( object sender, RoutedEventArgs e ) {
            Value += 0.01;
            UpdateTextBox();
        }

        private void InputBox_LostFocus( object sender, RoutedEventArgs e ) {
            if ( InputBox.Text.Length == 0 ) {
                Value = 0;
                return;
            }

            try {
                Value = double.Parse( InputBox.Text ) * 0.01;
            } catch ( Exception Exc ) {
                //UpdateTextBox();
            }
        }
    }
}
